package uk.co.richardwkirk.parkrun.android;

import java.util.LinkedList;
import java.util.List;

import uk.co.richardwkirk.parkrun.android.dataload.LoadDataDisplay;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

public abstract class SharedDataReadyActivity extends Activity {

	protected void useCountry(int requestCode) {
		String defaultCountry = getDefaultCountry();
		if (defaultCountry == null) {
			changeDefaultCountry(requestCode);
		}
		else {
			Intent intent = new Intent(this, LoadDataDisplay.class);
			intent.putExtra(IntentExtras.EXTRA_SELECTED_COUNTRY, defaultCountry);
			handleCountrySelectionResult(requestCode, intent);
		}
	}
	
	protected void changeDefaultCountry(int requestCode) {
		Intent intent = new Intent(this, CountrySelectionDisplay.class);
		startActivityForResult(intent, requestCode);
	}
	
	protected String getDefaultCountry() {
		SharedPreferences settings = getSharedPreferences(AppSettings.PARKRUN_SHARED_PREFS, 0);
		String defaultCountry = settings.getString(AppSettings.PREFS_DEFAULT_COUNTRY, null);
		return defaultCountry;
	}
	
	protected void loadEventData(int requestCode) {
		if (ParkrunEventData.getSingleton().isLoaded()) {
			// Event data is ready, skip ahead
			handleEventLoadResponse(requestCode);
		}
		else {
			// Start an activity to load the event data
			Intent intent = new Intent(this, LoadDataDisplay.class);
			intent.putExtra(IntentExtras.EXTRA_DATA_LOAD_TYPE, IntentExtras.DATA_LOAD_TYPE_EVENT_DATA);
			startActivityForResult(intent, requestCode);
		}
	}
	
	protected void doAthleteLoad(long athleteNumber, boolean reload) {
		this.setTitle("Loading Athlete...");
		List<Long> athleteNumbers = new LinkedList<Long>();
		athleteNumbers.add(athleteNumber);
		loadAthleteData(IntentExtras.REQUEST_ATHLETE_DATA_LOAD, athleteNumbers, reload);
	}
	
	protected void loadAthleteData(int requestCode, List<Long> athleteNumbers, boolean reload) {
		// Start load of the athlete
		Intent loadDataIntent = new Intent(this, LoadDataDisplay.class);
		loadDataIntent.putExtra(IntentExtras.EXTRA_DATA_LOAD_TYPE, IntentExtras.DATA_LOAD_TYPE_ATHLETE_DATA);
		loadDataIntent.putExtra(IntentExtras.EXTRA_DATA_LOAD_FORCE_RELOAD, reload);
		loadDataIntent.putExtra(IntentExtras.EXTRA_DATA_LOAD_ID, athleteNumberList(athleteNumbers));
		startActivityForResult(loadDataIntent, requestCode);
	}
	
	private String athleteNumberList(List<Long> athleteNumbers) {
		StringBuilder numberList = new StringBuilder();
		for (Long athlete : athleteNumbers) {
			numberList.append(athlete).append(",");
		}
		return numberList.toString();
	}

	/** 
	 * Handle activity results for requests we have invoked.
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("PARKRUN", "Country / Event data loaded:" + requestCode);
		switch (requestCode) {
			case IntentExtras.REQUEST_EVENT_DATA_LOAD_ONLY:
			case IntentExtras.REQUEST_EVENT_DATA_LOAD_COUNTRY_SELECTION:
			case IntentExtras.REQUEST_EVENT_DATA_LOAD_ALL_EVENTS:
			case IntentExtras.REQUEST_EVENT_DATA_LOAD_CLOSEST_EVENT:
			case IntentExtras.REQUEST_EVENT_DATA_LOAD_NEWS:
			case IntentExtras.REQUEST_EVENT_DATA_COMPARE_ATHLETE_EVENTS:
				eventSelection(requestCode, resultCode, data);
				break;
			case IntentExtras.REQUEST_COUNTRY_SELECT_ONLY:
			case IntentExtras.REQUEST_NEWS_COUNTRY_SELECT:
			case IntentExtras.REQUEST_EVENT_COUNTRY_SELECT:
			case IntentExtras.REQUEST_CHANGE_DEFAULT_COUNTRY:
				countrySelection(requestCode, resultCode, data);
				break;
			case IntentExtras.REQUEST_ATHLETE_DATA_LOAD:
				athleteLoad(requestCode, resultCode, data);
				break;
			default:
				Log.w("PARKRUN", "Unhandled activity result for request code: " + requestCode);
		}
	}
	
	
	private void eventSelection(int requestCode, int resultCode, Intent data)	{
		if (resultCode == RESULT_OK) {
			handleEventLoadResponse(requestCode);
		}
		else {
			reportError("Failed to load parkrun event data.");
		}
	}
	
	
	private void countrySelection(int requestCode, int resultCode, Intent data)	{
		String toastText = null;
		if (resultCode == RESULT_OK) {
			String country = data.getStringExtra(IntentExtras.EXTRA_SELECTED_COUNTRY);
			
			// Edit the shared preferences
			SharedPreferences settings = getSharedPreferences(AppSettings.PARKRUN_SHARED_PREFS, 0);
		    SharedPreferences.Editor editor = settings.edit();
		    editor.putString(AppSettings.PREFS_DEFAULT_COUNTRY, country);

		    // Commit the edits!
		    editor.commit();
		    
			toastText = "Country has been set to:" + country;
			
			// Do whatever the activity specifies
			handleCountrySelectionResult(requestCode, data);
		}
		else if (resultCode == RESULT_CANCELED) {
			toastText = "No country selected.";
		}
		else {
			toastText = "Failed to select a country.";
		}
		
		Toast toast = Toast.makeText(getApplicationContext(), toastText, AppSettings.INFO_DISPLAY_TIME);
		toast.show();
	}
	
	private void athleteLoad(int requestCode, int resultCode, Intent data)	{
		if (resultCode == RESULT_OK) {
			handleAthleteLoadResponse(requestCode);
		}
		else {
			reportError("Failed to load parkrun athlete data.");
			handleDataLoadError(requestCode);
		}
	}
	
	void reportError(String reason) {
		Log.e("PARKRUN", "Error loading data:" + reason);
		Toast toast = Toast.makeText(getApplicationContext(), reason, AppSettings.WARNING_DISPLAY_TIME);
		toast.show();
	}

	protected abstract void handleEventLoadResponse(int requestCode);
	protected abstract void handleCountrySelectionResult(int requestCode, Intent data);
	protected abstract void handleAthleteLoadResponse(int requestCode);
	protected abstract void handleDataLoadError(int requestCode);
	protected abstract void handleDataLoadCancel(int requestCode);
	
}
